package me.boot.auth.jap.controller;

import com.fujieid.jap.core.JapUserService;
import com.fujieid.jap.core.config.AuthenticateConfig;
import com.fujieid.jap.core.config.JapConfig;
import com.fujieid.jap.core.result.JapResponse;
import com.fujieid.jap.core.strategy.JapStrategy;
import com.fujieid.jap.http.JapHttpRequest;
import com.fujieid.jap.http.JapHttpResponse;
import me.boot.auth.jap.Util;
import me.boot.auth.jap.config.AuthProperties;
import me.boot.auth.jap.config.AuthStrategy;
import me.boot.auth.jap.config.JapConfigContext;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BaseAuthController<T extends JapStrategy> implements InitializingBean {

    @Autowired
    protected AuthProperties properties;
    protected T japStrategy;

    protected abstract AuthStrategy getAuthStrategy();

    protected abstract JapUserService getUserService();

    protected abstract T getJapStrategy(JapUserService japUserService, JapConfig japConfig);

    protected abstract AuthenticateConfig getAuthenticateConfig(AuthProperties.Platform platform);


    @RequestMapping("/login/{platformId}")
    public JapResponse renderAuth(HttpServletRequest request,
                                  HttpServletResponse response,
                                  @PathVariable("platformId") String platformId) {
        JapConfigContext.strategy = getAuthStrategy().name();
        AuthProperties.Platform platform = getPlatformProperties(platformId);
        AuthenticateConfig authConfig = getAuthenticateConfig(platform);
        JapHttpRequest japHttpRequest = Util.request(request);
        JapHttpResponse japHttpResponse = Util.response(response);
        return japStrategy.authenticate(authConfig, japHttpRequest, japHttpResponse);
    }


    /**
     * 初始化 bean 时对 oauth2Strategy 进行初始化，适用于启用了 SSO 的情况
     * 如果没有启用 SSO，则非强制使用该方式初始化
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        japStrategy = getJapStrategy(getUserService(), JapConfigContext.getConfig());
    }

    protected AuthProperties.Platform getPlatformProperties(String platformId) {
        return properties.getPlatforms().get(platformId);
    }
}
